const query = require('../../models');
const jwt = require('jsonwebtoken');
const { jwtConfig } = require('../../config');
const { decryptPassword, encryptedPassword } = require('../../utils/md5');

module.exports = {
  login(req, res) {
    const sql = `select * from admin_users where user_name=?`;
    const { username, password } = req.body;
    console.log('密码加密后：', encryptedPassword(password));

    query(sql, [username])
      .then(result => {

        if (result.length > 0) {
          const nowPass = decryptPassword(password, result[0].user_pass.substr(0, 8));

          if (nowPass == result[0].user_pass) {
            const token = jwt.sign({
              user_name: req.body.name
            }, jwtConfig.secretBack, { // 秘钥
              expiresIn: 60 * 60 // 过期时间
            });

            res.json({
              code: '200',
              errMsg: '登录成功',
              data: {
                userId: result[0].user_id,
                username: result[0].user_name,
                avator: result[0].avator,
                token
              }
            });
          } else {
            res.json({
              code: '1005',
              errorMsg: '账号或者密码错误'
            })
          }
        } else {
          res.json({
            code: '1005',
            errorMsg: '账号或者密码错误'
          })
        }
      })
      .catch(err => {
        res.json({
          code: '1001',
          errorMsg: '操作失败',
          err: err
        })
      });
  },
  logout(req, res) {
    res.json({
      code: '200',
      errMsg: '退出成功',
      data: {}
    })
  },
  forgetPassword(req, res) {
    const sql = ``;

    query(sql, [])
      .then(result => {
        res.json({
          code: '200',
          errMsg: '操作成功',
          data: {}
        })
      })
      .catch(err => {
        res.json({
          code: '1001',
          errorMsg: '操作失败',
          err: err
        })
      });
  },
  changePassword(req, res) {
    const sql = ``;

    query(sql, [])
      .then(result => {
        res.json({
          code: '200',
          errMsg: '操作成功',
          data: {}
        })
      })
      .catch(err => {
        res.json({
          code: '1001',
          errorMsg: '操作失败',
          err: err
        })
      });
  }
}